package com.doform.android.xianggucheng.retrofit.ApiSpecTransformer;

import android.view.View;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-20.
 * GitHub：https://github.com/cxydxpx
 */

public class DialogTransformer<T> implements ObservableTransformer<T, T> {

    private View mView;
    public DialogTransformer(View view) {
        if (view == null) {
            throw new NullPointerException();
        }
        mView = view;
    }

    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> upstream) {

        return upstream.observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                       mView.setVisibility(View.VISIBLE);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        mView.setVisibility(View.GONE);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        mView.setVisibility(View.GONE);
                    }
                });
    }
}
